import os
import socket
import time

import psutil

from utils.log import log


class Server:
    def __init__(self, port, request):
        self.size = 1024 * 1024 * 5
        self.request = request
        self.server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        # 绑定端口
        self.server.bind(('127.0.0.1', port))
        self.manage()

    def manage(self):
        while True:
            recv_data = self.server.recvfrom(self.size)  # size表示本次接收的最大字节数
            self.request(recv_data)

    def close(self):
        self.server.close()


class logRPC(Server):
    def __init__(self):
        self.log = log()
        super().__init__(5656, self.request)

    def request(self, re):
        data: str = re[0].decode("utf-8").split(":::")
        match data[0]:
            case "error":
                self.log.error(data[1], data[2], data[3], data[4])
            case "warn":
                self.log.warn(data[1], data[2], data[3], data[4])
            case "info":
                self.log.info(data[1], data[2], data[3], data[4])
            case "Critical":
                self.log.Critical(data[1], data[2], data[3], data[4])
            case "close":
                self.close()

    def close(self):
        while True:
            if len(self.log) > 0:
                time.sleep(1)
            else:
                psutil.Process(os.getpid()).kill()
